<?php
// 数据库连接
$host = 'localhost';
$dbname = 'message_board';
$user = 'root';
$pass = 'root';

$pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $user, $pass);
// echo '<pre>';print_r($_POST);die;
// 处理表单提交（添加和删除）
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $action = $_POST['action'];
    
    if ($action == 'add') {
        // 添加留言
        $name = $_POST['name'];
        $message = $_POST['message'];
        
        $stmt = $pdo->prepare("INSERT INTO messages (name, message) VALUES (?, ?)");
        $stmt->execute([$name, $message]);

    } elseif ($action == 'delete') {
        // 删除留言
        $id = $_POST['id'];

        $stmt = $pdo->prepare("DELETE FROM messages WHERE id = ?");
        $stmt->execute([$id]);
    }
    
    header('Location: message.php');
    exit;
}

// 显示留言列表
echo "<h3>留言列表</h3>";

$stmt = $pdo->query("SELECT * FROM messages ORDER BY id DESC");
$messages = $stmt->fetchAll();

if (empty($messages)) {
    echo "<p>还没有留言</p>";
} else {
    foreach ($messages as $msg) {
        $html = "
                <div style='border:1px solid #000;'>
                    <b>{$msg['name']}</b> - {$msg['created_at']}
                    <br>
                    {$msg['message']}
                    <br>
                    <br>
                    <form method='POST' style='display:inline;'>
                        <input type='hidden' name='action' value='delete'>
                        <input type='hidden' name='id' value='{$msg['id']}'>
                        <input type='submit' value='删除' onclick='return confirm(\"确定删除吗？\")'>
                    </form>
                </div>";
        echo $html;
    }
}

?>

<!-- 返回首页链接 -->
<br>
<a href="index.html">返回首页</a>